<!-- template必须, 只能有一个根标签, 影响渲染到页面的标签结构 -->
<template>
  <div>
    <!-- 角色管理的用户模块 -->
    <div class="container">
      <span class="source">关键字</span>
      <el-input
        class="source"
        placeholder="角色名称"
        v-model.trim="sourceRoleName"
        style="width: 200px"
        @keyup.enter.native="sourceButton(1)"
      />
      <el-button class="source" type="primary" @click="sourceButton(1)"
        >搜索</el-button
      >
      <el-button class="source" @click="sourceButton(0)">重置</el-button>
    </div>
    <!-- 数据渲染：表格显示 -->
    <div class="container">
      <el-button class="source" type="success" @click="addItem(0)"
        >+ 新增</el-button
      >
      <!-- 添加角色的弹窗 -->
      <el-dialog
        v-model="dialogFormVisible"
        :title="operateName"
        width="50%"
        draggable
        @open="openItem"
      >
        <el-form :model="formInfo">
          <el-form-item label="角色名称" label-width="120px" required>
            <el-input
              v-model="formInfo.rname"
              placeholder="请输入角色名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色编码" label-width="120px" required>
            <el-input
              v-model="formInfo.number"
              placeholder="请输入角色编码"
            ></el-input>
          </el-form-item>
          <el-form-item lable="状态" label-width="120px" required>
            <!-- flex  -->
            <div class="mb-2 items-center text-sm">
              <el-radio-group v-model="formInfo.state" class="ml-4">
                <el-radio :v-model="radio1" label="1" size="large"
                  >正常</el-radio
                >
                <el-radio :v-model="radio0" label="0" size="large"
                  >停用</el-radio
                >
              </el-radio-group>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="concelItem(0)">取消</el-button>
            <!-- 新增角色 -->
            <el-button
              type="primary"
              v-if="operateName == '新增角色'"
              @click="concelItem(1)"
            >
              提交
            </el-button>
            <!-- 修改角色信息 -->
            <el-button type="primary" v-else @click="concelItem(2)">
              提交
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 进行批量删除 -->
      <el-button class="source" type="danger" @click="toBatchDelete"
        >删除</el-button
      >

      <!-- 分隔线 -->
      <el-divider />
      <el-table
        :data="roleEntityList"
        border
        style="width: 100%; margin-top: 20px"
        ref="table"
        @selection-change="handleSelectionChange"
      >
        <!-- 选项 -->
        <el-table-column type="selection" width="60" />

        <!-- 角色名称 -->
        <el-table-column prop="rname" label="角色名称" width="180" />
        <!-- 角色编号 -->
        <el-table-column prop="number" label="角色编码" width="180" />
        <!-- 状态 -->
        <el-table-column prop="state" label="状态" width="180">
          <template #default="scope">
            <el-button v-if="scope.row.state == 1" type="success" plain
              >正常</el-button
            >
            <el-button v-else type="warning" plain>禁用</el-button>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作">
          <template #default="scope">
            <el-link
              size="small"
              type="primary"
              class="source"
              @click="sssignPermissions(scope.$index, scope.row)"
              >分配权限</el-link
            >
            <el-link
              size="small"
              type="primary"
              class="source"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-link
            >
            <el-link
              size="small"
              type="primary"
              class="source"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 弹窗组件   == 分配权限 -->
      <el-dialog v-model="showAssign" title="分配权限" @close="closeDialog">
        <el-tree
          ref="permissionTree"
          :data="data"
          :check-strictly="isBind"
          show-checkbox
          node-key="pid"
          :default-expand-all="true"
          :default-checked-keys="defaultKeyList"
          :props="defaultProps"
        />

        <template #footer>
          <span class="dialog-footer">
            <el-button type="info" @click="concelAssignPermissions(0)"
              >取消</el-button
            >
            <el-button type="warning" @click="concelAssignPermissions(1)">
              重置
            </el-button>
            <!-- 修改角色信息 -->
            <el-button type="primary" @click="concelAssignPermissions(2)">
              确认提交
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 分隔线 -->
      <el-divider />

      <!-- 分页按钮 -->
      <el-button v-if="currentPage == 1" type="info" @click="noPage" disabled
        >上一页</el-button
      >
      <el-button v-else type="primary" @click="toPrevious">上一页</el-button>
      <span class="source">{{ currentPage }}</span>

      <el-button
        v-if="currentPage == pages"
        type="info"
        @click="noPage"
        disabled
        >下一页</el-button
      >
      <el-button v-else type="primary" @click="toNext">下一页</el-button>

      <span class="source">总记录数：{{ total }}</span>
      <span class="source">总页数：{{ pages }}</span>
    </div>
  </div>
</template>

<!-- js相关 -->
<script>
import { getCurrentScope } from "vue";
export default {
  inject: ["reload"], //注入依赖
  name: "App",
  components: {},
  data() {
    return {
      // 存放变量，如下（数组，字符串，数字，对象）
      // 查询角色名称
      sourceRoleName: "",
      // 角色对象数组
      roleEntityList: [],
      // 当前页；
      currentPage: 1,
      // 总记录数；
      total: 0,
      // 总页数
      pages: 0,

      index: 0,
      // 控制删除弹窗
      isDelete: true,

      // 设置弹窗的显示
      dialogFormVisible: false,
      // 添加/修改角色的信息
      formInfo: {},
      // 新增角色 | 修改角色
      operateName: "",
      // 记录修改，删除，分配权限的角色（下标,对象）
      subscript: "",
      object: "",
      // 选中的行
      changeRow: [],
      // 进行批量删除rid的数组
      deleteRidList: [],

      // 存放变量，如下（数组，字符串，数字，对象）
      defaultProps: {
        children: "children",
        label: "pname",
      },
      data: [],
      // 默认选中的节点pid数组；
      defaultKeyList: [],
      showAssign: false,
      // 父节点与子节点是否关联
      isBind: false,
      // 半选中数组；
      halfCheckedKeys: [],
      // 全选中数组；
      checkedKeys: [],
      id: "",
      radio1: 1,
      radio0: 0,
    };
  },
  // 声明方法
  methods: {
    addItem(change) {
      this.formInfo = {};
      // 进行添加列表；
      if (change == 0) {
        this.operateName = "新增角色";
      } else {
        this.operateName = "修改角色";
        // 请求查询角色信息；（根据rid进行查询角色信息）
        this.$axios({
          url: "admin/role/selectRoleId",
          methods: "post",
          params: {
            rid: this.object.rid,
          },
        }).then((res) => {
          // 更新数组信息
          this.sourceButton(1);
          if (res.data != null || res.data != "") {
            this.formInfo = res.data;
            if (res.data.state == 0) {
              this.radio0 = this.formInfo.state;
              this.radio1 = 1;
            } else if (res.data.state == 1) {
              this.radio0 = 0;
              this.radio1 = this.formInfo.state;
            }
          } else {
            return;
          }
        });
      }

      this.dialogFormVisible = true;
    },
    concelItem(flag) {
      // 进行添加列表；
      this.dialogFormVisible = false;
      if (flag == 0) {
        // 取消按钮
        return;
      } else if (flag == 1) {
        // 提交
        // 添加角色的请求
        this.$axios({
          url: "admin/role/addRole",
          method: "post",
          params: {
            rname: this.formInfo.rname,
            number: this.formInfo.number,
            state: this.formInfo.state,
          },
        }).then((res) => {
          if (res.data.role == null) {
            ElMessage({
              showClose: true,
              message: "新增角色失败",
              type: "error",
              offset: 20,
            });
            // alert("新增角色失败");
          } else {
            ElMessage({
              showClose: true,
              message: "新增角色成功",
              type: "success",
              offset: 20,
            });
            // alert("新增角色成功" + res.data.role);
          }
          // 更新数组信息
          this.sourceButton(1);
        });
      } else if (flag == 2) {
        // 提交
        // 修改角色的请求
        this.$axios({
          url: "admin/role/updateRoleInfo",
          methods: "post",
          params: {
            rid: this.object.rid,
            rname: this.formInfo.rname,
            number: this.formInfo.number,
            state: this.formInfo.state,
          },
        }).then((res) => {
          if (res.data != null) {
            // alert("修改信息成功");
            ElMessage({
              showClose: true,
              message: "修改角色信息成功",
              type: "success",
              offset: 20,
            });
            // 更新数组信息
            this.sourceButton(1);
          } else {
            // alert("修改角色信息失败");
            ElMessage({
              showClose: true,
              message: "修改角色信息失败",
              type: "error",
              offset: 20,
            });
          }
        });
      }
    },

    // 获取选择中的行
    handleSelectionChange(val) {
      this.changeRow = val;
      // 清空数组
      this.deleteRidList = [];
      for (let i = 0; i < this.changeRow.length; i++) {
        this.deleteRidList.unshift(this.changeRow[i].rid);
      }
    },
    // 进行批量删除
    toBatchDelete() {
      if (this.deleteRidList.length != 0) {
        // 发送请求，进行批量进行删除
        // 移除数组中的数据；
        // 发送删除角色的请求
        this.$axios({
          url: "admin/role/deleteBatchById",
          method: "post",
          data: this.deleteRidList,
        }).then((res) => {
          if (res.data == true) {
            // alert("OK,已删除");
            ElMessage({
              showClose: true,
              message: "角色已被停用",
              type: "success",
              offset: 20,
            });
            // 前端进行删除元素
            this.sourceButton(1);
            this.deleteRidList = [];
          } else {
            // 删除元素失败
            ElMessage({
              showClose: true,
              message: "删除角色信息失败，请重试",
              type: "error",
              offset: 20,
            });

            // alert("删除元素失败，请重试");
          }
        });
      }
    },
    sourceButton(flag) {
      if (flag == 1) {
        // 进行搜索
        if (this.sourceRoleName == "") {
          // 进行全表查询
          this.$axios({
            url: "admin/role/selectAll",
            method: "post",
            params: {
              currentPage: this.currentPage,
            },
          }).then((res) => {
            this.setPageInfo(res.data);
          });
        } else {
          // 进行模糊查询
          this.$axios({
            url: "admin/role/selectAll",
            method: "post",
            params: {
              roleName: this.sourceRoleName,
              currentPage: this.currentPage,
            },
          }).then((res) => {
            this.setPageInfo(res.data);
          });
        }
      } else {
        // 重置
        this.sourceRoleName = "";
      }
    },

    // 给角色分配权限
    sssignPermissions(index, row) {
      // 对角色的状态进行判断
      if (row.state == 0) {
        ElMessage({
          showClose: true,
          message: "该角色已被禁用，无法进行权限分配",
          type: "warning",
        });
        // alert("该角色已被禁用，无法进行权限分配");

        return;
      }
      // 设置弹窗
      this.subscript = index;
      this.object = row;
      this.id = this.object.rid;
      // 开启分配权限的弹窗
      this.init();
      this.showAssign = true;
    },

    // 分配权限的三个按钮；
    concelAssignPermissions(flag) {
      if (flag == 0) {
        // 取消：重置数据，并退出弹窗；
        // 设置退出弹窗
        this.showAssign = false;
        // 重置数据；
        this.init();
      } else if (flag == 1) {
        // 重置： 重置数据；
        this.init();
      } else if (flag == 2) {
        // 确认提交:保存数据，并退出
        // 获取最新的数据；
        let permissionPidList = [];

        this.halfCheckedKeys = [];
        // this.halfCheckedKeys = this.halfCheckedKeys.unshift(this.$refs.permissionTree.getHalfCheckedKeys());
        this.halfCheckedKeys = this.$refs.permissionTree.getHalfCheckedKeys();

        this.checkedKeys = [];
        // this.checkedKeys = this.checkedKeys.unshift(this.$refs.permissionTree.getCheckedKeys());
        this.checkedKeys = this.$refs.permissionTree.getCheckedKeys();

        permissionPidList = this.halfCheckedKeys;
		
		for(let i = 0; i < this.checkedKeys.length; i++) {
			permissionPidList.unshift(this.checkedKeys[i]);
		}
        let obj = {
          list: permissionPidList,
          id: this.id,
        };
        console.log(obj);
        // 发送提交请求；角色-权限；
        this.$axios({
          url: "admin/rolePermission/updateRolePermissionPid",
          method: "post",
          headers: {
            "Content-Type": "application/json",
          },
          data: JSON.stringify(obj),
        }).then((res) => {
          if (res.data == true) {
            // alert("角色-权限 修改成功！");
            ElMessage({
              showClose: true,
              message: "角色-权限 修改成功！",
              type: "success",
              offset: 20,
            });
          } else {
            // alert("角色-权限 修改失败！请重试！");
            ElMessage({
              showClose: true,
              message: "角色-权限 修改失败！请重试！",
              type: "error",
              offset: 20,
            });
          }
          // 刷新数据
          this.init();
          // 重写刷新整页面；
          this.reload();

          // 设置退出弹窗
          this.showAssign = false;
        });
      }
    },
    // 数据初始化；
    init() {
      this.defaultKeyList = [];
      // 渲染树结构
      this.$axios({
        url: "admin/permission/selectPermissionInfo",
        methods: "post",
      }).then((res) => {
        this.data = [];
        this.data = res.data;
      });
      // 数据渲染时，取消关联
      this.isBind = true;

      // 渲染树选择的数据；
      this.$axios({
        url: "admin/rolePermission/selectPermissionPid",
        methods: "post",
        params: {
          rid: this.id,
        },
      }).then((res) => {
        let list = res.data;
        this.defaultKeyList = [];
        for (let i = 0; i < list.length; i++) {
          this.defaultKeyList.unshift(list[i].pid);
          console.log(list[i].pid);
        }
      });
      this.$nextTick(() => {
        // 数据渲染完成，和用户交互；
        this.isBind = false;
      });
    },
    // 弹窗关闭时回调
    closeDialog() {
      this.defaultKeyList = [];
      this.init();
    },
    // 编辑角色
    handleEdit(index, row) {
      // 设置弹窗
      this.subscript = index;
      this.object = row;
      this.radio = row.state;
      this.addItem(1);
    },
    // 删除角色
    handleDelete(index, row) {
      // 先查询这个角色的状态信息；
      this.sourceButton(1);
      if (row.state == 0) {
        ElMessage({
          showClose: true,
          message: "该角色已被禁用，无法进行删除操作",
          type: "warning",
        });
      }

      this.isDelete = true;
      this.$nextTick(() => {
        this.toDeleteOneRole(index, row);
      });
    },
    toDeleteOneRole(index, row) {
      var content;

      this.deleteRidList = [];
      this.deleteRidList.unshift(row.rid);
      if (confirm("你确定要删除这个角色吗？")) {
        //if语句内部判断确认框
        //若点击了确认，返回true，执行1
        // 发送删除角色的请求
        this.$axios({
          url: "admin/role/deleteBatchById",
          method: "post",
          data: this.deleteRidList,
        }).then((res) => {
          // alert("删除是否成功：" + res.data);
          if (res.data == true) {
            ElMessage({
              showClose: true,
              message: "已成功删除角色",
              type: "success",
              offset: 20,
            });
            // 前端进行删除元素
            this.sourceButton(1);
            this.deleteRidList = [];
          } else {
            // 删除元素失败
            // alert("删除元素失败，请重试");
            ElMessage({
              showClose: true,
              message: "删除角色失败，请重试",
              type: "error",
              offset: 20,
            });
          }
        });
      } else {
        //若点击了取消，则返回false，执行2
        return;
      }
    },
    // 没有页数进行显示
    noPage() {
      return;
    },
    // 下一页
    toNext() {
      this.currentPage++;
      this.sourceButton(1);
    },
    // 上一页
    toPrevious() {
      this.currentPage--;
      this.sourceButton(1);
    },
    setPageInfo(data) {
      // 角色对象数组
      this.roleEntityList = data.list;
      // 当前页；
      this.currentPage = data.current;
      // 总记录数；
      this.total = data.total;
      // 总页数
      this.pages = data.pages;
    },
  },
  created() {
    console.log("当前页数：" + this.currentPage);
    // 进行全表查询
    this.$axios({
      url: "admin/role/selectAll",
      method: "post",
      params: {
        currentPage: this.currentPage,
      },
      dataType: "json",
      contentType: "application/json; charset=UTF-8",
    }).then((res) => {
      this.setPageInfo(res.data);
    });
    this.init();
  },
};
</script>

<!-- 当前组件的样式, 设置scoped, 可以保证样式只对当前页面有效 -->
<style scoped>
.container {
  padding: 18px;
  margin: 10px 0px;
}

.container .source {
  margin: 0px 20px;
}

.el-button--text {
  margin-right: 15px;
}

.el-input {
  width: 300px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

.tree-wrapper {
  max-width: 500px;
}

.label {
  font-size: 14px;
}

.el-button--text {
  margin-right: 15px;
}

.el-input {
  width: 300px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
